package net.koodar.forge.system.dept.service.assembler;

import net.koodar.forge.system.dept.model.dto.DeptParamDTO;
import net.koodar.forge.system.dept.model.entity.Dept;
import net.koodar.forge.system.dept.model.vo.DeptVO;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liyc
 */
@Component
public class DeptAssembler {

    public List<DeptVO> convertToTree(List<Dept> deptList, List<Dept> allDeptList) {

        if (deptList == null) {
            deptList = allDeptList.stream()
                    .filter(permission -> permission.getParentId() == null)
                    .toList();
        }

        List<DeptVO> menuVos = new ArrayList<>();
        for (Dept dept : deptList) {
            DeptVO deptVo = convertToDeptVO(dept);
            List<Dept> childrenList = allDeptList.stream()
                    .filter(p -> p.getParentId() != null && p.getParentId().equals(dept.getId()))
                    .collect(Collectors.toList());
            if (!deptList.isEmpty()) {
                List<DeptVO> children = convertToTree(childrenList, allDeptList);
                deptVo.setChildren(children);
            }
            menuVos.add(deptVo);
        }
        return menuVos;
    }

    public DeptVO convertToDeptVO(Dept dept) {
        DeptVO deptVO = new DeptVO();
        deptVO.setId(dept.getId());
        deptVO.setParentId(dept.getParentId());
        deptVO.setDeptName(dept.getDeptName());
        deptVO.setSort(dept.getSort());
        return deptVO;
    }

    public Dept convertToDept(DeptParamDTO deptParamDTO) {
        return convertToDept(new Dept(), deptParamDTO);
    }

    public Dept convertToDept(Dept dept, DeptParamDTO deptParamDTO) {
        dept.setParentId(deptParamDTO.getParentId());
        dept.setDeptName(deptParamDTO.getDeptName());
        dept.setSort(deptParamDTO.getSort());
        dept.setId(deptParamDTO.getId());
        return dept;
    }

}
